package com.example.lib_common.base

import android.R.attr.type
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.activity.ComponentActivity
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import androidx.viewbinding.ViewBinding
import java.lang.reflect.ParameterizedType

fun <VB : ViewBinding> Any.getViewBinding(
    inflater: LayoutInflater
): VB {
    val vbClass =
        (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments.filterIsInstance<Class<*>>()
    val inflate = vbClass[0].getDeclaredMethod("inflate", LayoutInflater::class.java)
    return inflate.invoke(null, inflater) as VB
}

fun <VM : ViewModel> ViewModelStoreOwner.createViewModel(
    factory: ViewModelProvider.Factory? = null,
): VM {
    val vbClass =
        (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments.filterIsInstance<Class<*>>()
    val viewModel = vbClass[1] as Class<VM>
    return factory?.let {
        ViewModelProvider(
            this,
            factory
        )[viewModel]
    } ?: ViewModelProvider(this)[viewModel]
}

@Suppress("UNCHECKED_CAST")
fun <VB : ViewDataBinding> Any.getItemViewBinding(
    inflater: LayoutInflater,
    parent: ViewGroup
): VB {
    // 1. 获取当前类的泛型父类信息
    val vbClass = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[1]  as Class<*>
    // ↑ 第二个泛型参数: DataBindingHolder<SimpleListItem2Binding>

    // 2. 解析 DataBindingHolder<XxxBinding> 的实际参数
//    val vbClass = (type as ParameterizedType).actualTypeArguments[0] as Class<*>
    // ↑ 这里就是 SimpleListItem2Binding.class

    // 3. 通过反射获取 inflate(LayoutInflater, ViewGroup, Boolean)
    val method = vbClass.getDeclaredMethod(
        "inflate",
        LayoutInflater::class.java,
        ViewGroup::class.java,
        Boolean::class.javaPrimitiveType
    )

    // 4. 调用静态方法 inflate() 生成 ViewDataBinding
    return method.invoke(null, inflater, parent, false) as VB
}
